<template>
  <div class="g-page-container">
    <PageHeader title="商机逾期报警数" />
    <div class="g-content-container">
      <SearchForm ref="search-form" @search="getList" @export="exportList" />
      <p-table
        class="table-list-container"
        row-key="id"
        :pagination="false"
        :data-source="formatList"
        :columns="columns"
        bordered
      />
    </div>
  </div>
</template>

<script>
import SearchForm from './components/SearchForm.vue';
let idKey = 0;
import mixinTable from '@/mixins/mixin-table.js';
import { downloadFile } from '@/utils/index.js';
import {
  postOverdueBusinessList,
  postlistExportTemplate,
} from '@/api/business';
export default {
  components: {
    SearchForm,
  },
  mixins: [mixinTable],
  data() {
    return {
      hasSearchName: true,
    };
  },
  computed: {
    formatList() {
      if (this.dataSource.length === 0) {
        return [];
      }
      const list = Object.keys(this.groups).map(group => {
        const data = this.groups[group] || [];
        const total = data.reduce((pre, cur) => {
          pre = pre + cur.count;
          return pre;
        }, 0);
        data.forEach(item => {
          item.total = total;
        });
        return [...data];
      });
      return [...list.flat(Infinity)];
    },
    groups() {
      return this.dataSource.reduce((pre, cur) => {
        if (pre[cur.salesGroupCode]) {
          pre[cur.salesGroupCode].push({ ...cur, id: ++idKey });
        } else {
          pre[cur.salesGroupCode] = [{ ...cur, id: ++idKey }];
        }
        return pre;
      }, {});
    },
    groupAndNames() {
      return Object.keys(this.groups).reduce((pre, cur) => {
        const ary = this.groups[cur];
        ary.reduce((p, c) => {
          const key = `${cur}_${c.uid}`;
          if (p[key]) {
            p[key] += 1;
          } else {
            p[key] = 1;
          }
          return p;
        }, pre);
        return pre;
      }, {});
    },
    groupAndNamesFirst() {
      return Object.keys(this.groupAndNames).reduce((pre, cur) => {
        const [salesGroupCode, uid] = cur.split('_');
        const item =
          this.formatList.find(
            item => item.salesGroupCode === salesGroupCode && item.uid === uid
          ) || {};
        const id = item.id;
        const key = `${cur}_${id}`;
        pre[key] = this.groupAndNames[cur];
        return pre;
      }, {});
    },
    orgOptions() {
      return this.$store.getters.getOrg({
        code: 'ltcsmsizebu',
      });
    },
    nodeOptions() {
      return (
        this.$store.state.dictionary.dict['business_stage_process_node'] || {}
      );
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '销售组织',
          dataIndex: 'salesOrgCode',
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'salesOrgCode');
          },
        },
        {
          align: 'center',
          title: '部门',
          dataIndex: 'salesGroupName',
          ellipsis: true,
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'salesGroupName');
          },
        },
        {
          align: 'center',
          title: '姓名',
          dataIndex: 'name',
          hasSearchName: !this.hasSearchName,
          ellipsis: true,
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'name');
          },
        },
        {
          align: 'center',
          title: '逾期次数',
          dataIndex: 'count',
          ellipsis: true,
          customRender: (value, row, index) => {
            return this.customRender(value, index, row, 'count');
          },
        },
        {
          align: 'center',
          title: '商机编号',
          dataIndex: 'opportunityNo',
          width: 160,
          ellipsis: true,
        },
        {
          align: 'center',
          title: '商机名称',
          dataIndex: 'opportunityName',
          ellipsis: true,
        },
        {
          align: 'center',
          title: '逾期发送阶段',
          dataIndex: 'opportunityStep',
          ellipsis: true,
          customRender: text => this.nodeOptions[text],
        },
      ];
      return columns.filter(item => !item.hasSearchName);
    },
  },

  mounted() {
    this.getList();
  },
  methods: {
    async exportList() {
      const form = this.$refs['search-form']?.form || {};
      const res = await postlistExportTemplate({
        asc: this.asc,
        column: this.columnKey,
        ...form,
      });
      await downloadFile(res.data, '商机逾期报警信息.xlsx');
    },
    getSearchForm() {
      const form = this.$refs['search-form']?.form || {};
      return { ...form, salesGroup: undefined, time: undefined };
    },
    async getList() {
      const form = this.getSearchForm();
      this.loading = true;
      this.hasSearchName = form.isFindName;
      const result = await postOverdueBusinessList(form).finally(
        () => (this.loading = false)
      );
      this.dataSource = result.data.data;
    },
    customRender(children, index, row, key) {
      const attrs = {};
      if (key === 'salesOrgCode') {
        children = this.orgOptions[children];
      }
      if (
        key === 'salesGroupName' ||
        key === 'salesOrgCode' ||
        (key === 'count' && !this.hasSearchName)
      ) {
        const data = this.groups[row.salesGroupCode] || [];
        if (row.id === data[0]?.id) {
          attrs.rowSpan = data.length;
        } else {
          attrs.rowSpan = 0;
        }
        return {
          children,
          attrs,
        };
      }
      if (key === 'name' || key === 'count') {
        const key = `${row.salesGroupCode}_${row.uid}_${row.id}`;
        attrs.rowSpan = this.groupAndNamesFirst[key] || 0;
      }
      return {
        children,
        attrs,
      };
    },
  },
};
</script>
